﻿using DataService.User;
using Cache.Redis;
using Common;
using Model.User;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using Model.Voyage;
using Service.Table;
using Model.Port;
using DataService.Port;

namespace Service.User
{
    /// <summary>
    /// AccountService 的摘要说明
    /// </summary>
    public class AccountService : IQueryInterface
    {
        /// 处理完数据，修改 d的值 d-Dictionary<string, object>
        /// <summary>
        /// 处理完数据，修改 d的值 d-Dictionary<string, object>
        /// </summary>
        /// <param name="param">传参ParamData</param>
        /// <param name="data"></param>
        public void GetData(string uid, Dictionary<string, object> p, ref Dictionary<string, object> d)
        {
            //返回数据d
            d.Add("error", 0);
            d.Add("uid", uid);
            d.Add("token", "");

            //result["d"] = d;

            try
            {

                if (p != null)
                {
                    AccountParam param = new AccountParam();
                    param.DeviceId = p.ContainsKey("deviceId") ? p["deviceId"].ToString() : "";
                    param.PlatOS = p.ContainsKey("platOS") ? Convert.ToInt32(p["platOS"]) : -1;
                    param.ChannelName = p.ContainsKey("channel") ? p["channel"].ToString() : "";
                    param.ChannelId = p.ContainsKey("channel_id") ? p["channel_id"].ToString() : "";

                    if (param.PlatOS < 0)
                    {
                        d["error"] = 1;  //平台错误
                        return;
                    }

                    //todo 判断渠道

                    //查询是否存在该账号
                    d["uid"] = AccountInfo.GetUIDByChannelIdOrDeviceId(param.ChannelId, param.DeviceId);
                    if (d["uid"] == null || d["uid"].ToString() == "")
                    {
                        //创建账号
                        d["uid"] = AccountInfo.SaveAccount(param);
                        if (d["uid"] == null || d["uid"].ToString() == "")
                        {
                            d["error"] = 3;    //账号创建失败
                            return;
                        }

                        //创建账号时，需要初始化其他数据信息
                        InitUserData(d["uid"].ToString());
                    }

                    //重新生成token
                    d["token"] = GetToken(d["uid"].ToString());
                    if (d["token"] == null || d["token"].ToString() == "")
                    {
                        d["error"] = 5;  //token生成失败
                        return;
                    }
                    //至此，处理成功
                }
            }
            catch (Exception ex)
            {
                throw new Exception("AccountService.GetData", ex);
            }
        }

        /// 创建账号时，需要初始化 角色、船舶、舰队、已探索海域、岛礁、岛礁路线、高级船员等信息
        /// <summary>
        /// 创建账号时，需要初始化 角色、船舶、舰队、已探索海域、岛礁、岛礁路线、高级船员等信息
        /// </summary>
        /// <param name="uid"></param>
        public void InitUserData(string uid)
        {
            TableService.GetTableObjectList<TableCommonProperty>(); //获取公共属性配置

            //创建角色
            RoleData role = new RoleData();
            role.UID = Convert.ToInt32(uid);
            role.Name = "test"; //todo 默认命名规则
            role.Gold = TableCommonProperty.init_gold;
            role.Diamond = TableCommonProperty.init_diamond;
            role.Food = TableCommonProperty.init_food;
            role.SeaMan = TableCommonProperty.init_seaman;
            role.WorkMan = TableCommonProperty.init_workman;
            role.Level = TableCommonProperty.init_level;
            role.DataFlag = 1;
            //RoleInfo.SaveRole(role, uid);
            //RedisHelper.instance.SaveHashObjectData<RoleData>(role);
            //DataBusiness.SaveObject<RoleData>(role);
            role.InsertData();

            //创建岛礁连线、岛礁、海域
            var con_id_list = TableCommonProperty.init_sea_connect; //配置表中岛礁连线配置
            //SeaConnectData con_data;
            //SeaPointData point_data;
            //SeaMaskData mask_data;
            SeaHelper.InitSeaMap(uid, con_id_list);
            //RedisHelper.instance.SaveHashObjectData<SeaConnectData>(con_data);
            //RedisHelper.instance.SaveHashObjectData<SeaPointData>(point_data);
            //RedisHelper.instance.SaveHashObjectData<SeaMaskData>(mask_data);

            //BuildingData _build_data = RedisHelper.instance.GetObjectDataByKey<BuildingData>(uid);
            //BuildingWorkTaskData _building_work_task_data = RedisHelper.instance.GetObjectDataByKey<BuildingWorkTaskData>(uid);
            //CollectPointData _collect_point_data = RedisHelper.instance.GetObjectDataByKey<CollectPointData>(uid);
            //LockZoneData _lock_zone_data = RedisHelper.instance.GetObjectDataByKey<LockZoneData>(uid);
            //RoadData _road_data = RedisHelper.instance.GetObjectDataByKey<RoadData>(uid);
            //RoadPointData _road_point_data = RedisHelper.instance.GetObjectDataByKey<RoadPointData>(uid);

            MapHelper.InitMap(uid);

            //_build_data.UID = uid;
            //RedisHelper.instance.SaveHashObjectData(_build_data);
            //_building_work_task_data.UID = uid;
            //RedisHelper.instance.SaveHashObjectData(_building_work_task_data);
            //_collect_point_data.UID = uid;
            //RedisHelper.instance.SaveHashObjectData(_collect_point_data);
            //_lock_zone_data.UID = uid;
            //RedisHelper.instance.SaveHashObjectData(_lock_zone_data);
            //_road_data.UID = uid;
            //RedisHelper.instance.SaveHashObjectData(_road_data);
            //_road_point_data.UID = uid;
            //RedisHelper.instance.SaveHashObjectData(_road_point_data);

            #region 读取配置表，添加岛礁连线、岛礁、海域

            ////创建连线
            //SeaConnectData con_data = new SeaConnectData();
            //con_data.UID = uid;
            //con_data.SeaConnectList = new List<SeaConnect>();
            //var con_id_list = TableCommonProperty.init_sea_connect;
            //if (con_id_list != null && con_id_list.Any())
            //{
            //    string[] con_keys = con_id_list.Select<int, string>(x => x.ToString()).ToList().ToArray();
            //    List<TableSeaConnect> table_conn_list = TableService.GetTableObjectListByKeys<TableSeaConnect>(con_keys);    //根据配置的连线，获取路线列表
            //    foreach (var c_item in table_conn_list)
            //    {
            //        SeaConnect con = new SeaConnect();
            //        con.Id = c_item.mId;
            //        con.VoyageCount = 0;
            //        con.Dangerous = c_item.mDangerous;

            //        con_data.SeaConnectList.Add(con);
            //    }
            //}
            //RedisHelper.instance.SaveHashObjectData<SeaConnectData>(con_data);

            ////创建岛礁
            //List<TableSeaMask> table_mask_list = TableService.GetTableObjectList<TableSeaMask>(); //获取海域表
            //var point_id_list = TableCommonProperty.init_sea_point;
            //SeaPointData point_data = new SeaPointData();
            //point_data.UID = uid;
            //point_data.SeaPointList = new List<SeaPoint>();
            //List<int> mask_id_list_have = new List<int>();  //玩家全部岛礁集合
            //if (point_id_list != null && point_id_list.Any())
            //{
            //    string[] point_keys = point_id_list.Select<int, string>(x => x.ToString()).ToList().ToArray();
            //    List<TableSeaPoint> table_point_list = TableService.GetTableObjectListByKeys<TableSeaPoint>(point_keys);    //根据默认岛礁id，获取岛礁id的详细信息

            //    foreach (var item in table_point_list)
            //    {
            //        SeaPoint point = new SeaPoint();
            //        point.Id = item.mId;
            //        point.Type = item.mType;
            //        point.Level = 1;
            //        point.Exp = 0;
            //        foreach (var m_item in table_mask_list)
            //        {
            //            if (m_item.mIncludePointId.Contains(point.Id))
            //            {
            //                point.MaskId = m_item.mId;

            //                //去重增加海域
            //                if (!mask_id_list_have.Contains(m_item.mId))
            //                {
            //                    mask_id_list_have.Add(m_item.mId);
            //                }
            //            }
            //        }

            //        point_data.SeaPointList.Add(point);
            //    }
            //}
            //RedisHelper.instance.SaveHashObjectData<SeaPointData>(point_data);

            ////创建海域
            //var mask_id_list = TableCommonProperty.init_sea_mask ?? new List<int>();   //属性配置中，可探索的海域id

            //SeaMaskData mask_data = new SeaMaskData();
            //mask_data.UID = uid;
            //mask_data.UnlockMask = mask_id_list;
            //mask_data.MaskCurrent = new List<SeaMask>();

            //if (mask_data.UnlockMask != null && mask_data.UnlockMask.Any())
            //{
            //    foreach (var item in mask_data.UnlockMask)
            //    {
            //        TableSeaMask t_mask = table_mask_list.Where(p => p.mId == item).FirstOrDefault();
            //        var explore_points = point_data.SeaPointList.Where(p => p.MaskId == item).Select(p => p.Id).ToList();
            //        if (explore_points != null && explore_points.Any())
            //        {
            //            if (explore_points.Count < t_mask.mIncludePointId.Count)
            //            {
            //                //未探索完全
            //                SeaMask mask = new SeaMask();
            //                mask.Id = item;
            //                mask.OwnPoints = explore_points;
            //                mask.ExploreRate = t_mask.mDetectRateBase;

            //                mask_data.MaskCurrent.Add(mask);
            //            }
            //        }
            //    }
            //}
            //RedisHelper.instance.SaveHashObjectData<SeaMaskData>(mask_data);

            #endregion 读取配置表，添加岛礁连线、岛礁、海域

            //创建高级船员
            List<Captain> captainList = new List<Captain>();
            var captain_list = TableCommonProperty.init_captain;   //属性配置中的高级船员
            if (captain_list != null && captain_list.Any())
            {
                //int captain_maxId = 0;
                foreach (var item in captain_list)
                {
                    Captain captain = new Captain();
                    //captain.Id = ++captain_maxId;
                    captain.UID = Convert.ToInt32(uid);
                    captain.TableId = item;
                    captain.Name = CaptainInfo.GetCaptainName();    //获取不重复姓名
                    Tuple<int, string> captain_icon = CaptainInfo.GetCaptainIcon(item);    //获取随机icon
                    captain.Icon = captain_icon.Item2;
                    captain.ShipTrainId = 0;
                    captain.Status = 0;
                    captain.Skills = CaptainInfo.GetCaptainSkill(); //随机获取技能
                    captain.DataFlag = 1;

                    captainList.Add(captain);
                }
            }
            //RedisHelper.instance.SaveRangeObjectInHash<Captain>(uid, captainList);
            DataBusiness.SaveObjectList<Captain>(captainList);

            //创建船舶
            List<Ship> shipList = new List<Ship>();
            var ship_list = TableCommonProperty.init_ship;  //Item1-ID；Item2-Num
            if (ship_list != null && ship_list.Any())
            {
                string[] ship_keys = ship_list.Select(p => p.Item1).ToList().Select<int, string>(x => x.ToString()).ToList().ToArray();
                List<TableSeaShip> table_ship_list = TableService.GetTableObjectListByKeys<TableSeaShip>(ship_keys);    //根据默认船舶id列表，获取信息

                //int ship_maxId = 0;
                foreach (var item in ship_list)
                {
                    TableSeaShip table_ship = table_ship_list.Where(p => p.mId == item.Item1).FirstOrDefault();
                    for (int i = 0; i < item.Item2; i++)
                    {
                        Ship ship = new Ship();
                        //ship.Id = ++ship_maxId;
                        ship.UID = Convert.ToInt32(uid);
                        ship.TableId = item.Item1;
                        ship.ShipTrainId = 0;
                        ship.Name = table_ship.mName;
                        ship.Durability = table_ship.mMaxDurable;
                        ship.LoadNum = 0;
                        ship.Speed = table_ship.mSpeedMin;
                        ship.SailorNum = 0;
                        ship.Supply = 0;
                        ship.Level = 1;
                        ship.Status = 0;
                        ship.FixStartTime = 0;
                        ship.FixTime = 0;
                        ship.DataFlag = 1;

                        shipList.Add(ship);
                    }
                }
            }
            //RedisHelper.instance.SaveRangeObjectInHash<Ship>(uid, shipList);
            DataBusiness.SaveObjectList<Ship>(shipList);

            //创建舰队
            List<ShipTrain> shipTrainList = new List<ShipTrain>();
            int maxShipNum = 10;
            //int shipTrain_maxId = 0;
            for (int i = 0; i < maxShipNum; i++)
            {
                ShipTrain shipTrain = new ShipTrain();
                //shipTrain.Id = ++shipTrain_maxId;
                shipTrain.UID = Convert.ToInt32(uid);
                shipTrain.Name = "";    //todo 命名规则
                shipTrain.Captain_Master = 0;
                shipTrain.Captain_Mate = 0;
                shipTrain.Captain_Helmsman = 0;
                shipTrain.Status = 0;
                shipTrain.ShipId = 0;
                shipTrain.DataFlag = 1;

                shipTrainList.Add(shipTrain);
            }
            //RedisHelper.instance.SaveRangeObjectInHash<ShipTrain>(uid, shipTrainList);
            DataBusiness.SaveObjectList<ShipTrain>(shipTrainList);
        }

        /// 生成token
        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public string GetToken(string uid)
        {
            //更新redis里面token信息
            string token = CheckInfo.ConvertTimeToUTCTimeStamp(DateTime.Now).ToString();
            var isSuccess = RedisHelper.instance.SetEntryInHash(LoginLogData.login_token, uid, token);

            AccountInfo.SaveLoginLog(uid, token);   //保存token日志

            return token;
        }

        /// 服务端实体与dictionary匹配
        /// <summary>
        /// 服务端实体与dictionary匹配
        /// </summary>
        /// <param name="res"></param>
        /// <returns></returns>
        public static void ModelMatch(AccountResponse res, ref Dictionary<string, object> list)
        {
            list.Add("error", res.error);
            list.Add("uid", res.uid);
            list.Add("token", res.token);
        }

    }
}
